import {
  MiddlewareConsumer,
  Module,
  NestModule,
  RequestMethod,
} from '@nestjs/common';
import { UserModule } from './user/user.module';
import { MongooseModule } from '@nestjs/mongoose';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { ResponseInterceptor } from './interceptors/response.interceptors';
import { AuthMiddleware } from './middleware/auth/auth.middleware';
import { UserController } from './user/user.controller';
import { TokenService } from './service/token.service';
import { RoleModule } from './role/role.module';
import { AuthGuard } from './guard/auth.guard';
import { RoleController } from './role/role.controller';
import { ScheduleModule } from '@nestjs/schedule';
import { TasksService } from './task/task.service';
import { LoggerModule, Logger } from 'nestjs-pino';
import { join } from 'path';
import { HttpExceptionFilter } from './filter/http-exception.filter';
@Module({
  imports: [
    // 定时任务
    ScheduleModule.forRoot(),
    // mongonDb
    MongooseModule.forRoot('mongodb://localhost:27017/nest'),
    UserModule,
    RoleModule,
    // 错误日志
    LoggerModule.forRoot({
      pinoHttp: {
        level: 'error',
        transport: {
          target: 'pino-roll',
          options: {
            file: join(__dirname, '../logs/logs.txt'),
            frequency: 'daily',
            size: '10M',
            mkdir: true,
          },
        },
      },
    }),
  ],
  providers: [
    Logger,
    // 全局异常过滤器
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter,
    },
    // 全局响应拦截器
    {
      provide: APP_INTERCEPTOR,
      useClass: ResponseInterceptor,
    },
    // 全局角色管道
    {
      provide: APP_GUARD,
      useClass: AuthGuard,
    },
    TokenService,
    // 定时任务,
    TasksService,
  ],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AuthMiddleware)
      .exclude(
        {
          path: '/user/login',
          method: RequestMethod.POST,
        },
        {
          path: '/user/code',
          method: RequestMethod.GET,
        },
      )
      .forRoutes(UserController, RoleController);
  }
}
